package com.itheima.controller;

import com.itheima.entity.TbUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("test")
    public String testRequestMapping(){
        return "helloRequestMapping";
    }

    @GetMapping("findUserById/{id}")
    public TbUser findUserById(@PathVariable("id")Integer id){

        /*
            1.url硬编码(写死了) ----》springcloud euraka（注册中心）
            2.负载均衡问题 ---》springcloud ribbon（负载均衡器）
            3.无法感知调用服务的状态 ---》springcloud hystrix（熔断器）
         */
        //String url = "http://localhost:9091/user/findUserById/" + id;

        /*
            通过注册中心服务列表的方式调用
            解决url硬编码
         */
        /*List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        URI uri = instances.get(0).getUri();
        String url = uri + "/tbUser/selectOne?id=" + id;*/
        String url = "http://user-service/tbUser/selectOne?id=" + id;
        TbUser user = restTemplate.getForObject(url, TbUser.class);
        return user;
    }

    @GetMapping("/getInstance")
    public List<ServiceInstance> getInstance() {
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        return instances;
    }
}
